package org.example.interceptor;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.example.client.ServiceBClient;
import org.example.dao.RouterRuleDao;
import org.example.dao.RouterparametersDao;
import org.example.po.Routerparameters;
import org.example.po.Routerrule;
import org.example.router.IRouter;
import org.example.router.impl.DefaultRouterImpl;
import org.example.utils.BeanFactoryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@Component
public class MyInterceptor implements HandlerInterceptor {
    public static final Logger LOGGER = LoggerFactory.getLogger(MyInterceptor.class);

    private RouterRuleDao routerRuleDao;


    public MyInterceptor(RouterRuleDao routerRuleDao) {
        this.routerRuleDao = routerRuleDao;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException{

        //根据handler获取url对应的方法名
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String methodName = handlerMethod.getMethod().getName();
        //当url没有对应的接口时，直接拦截
        if("error".equals(methodName)){
            return false;
        }

        String tradeCode = methodName.substring(2);

        MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper(request);
        String body = requestWrapper.getBody();
        Map<String,String> map = JSON.parseObject(body, Map.class);
        map.put("rulename", tradeCode);
        map.put("method",methodName);
        // 通过交易码获取指定路由策略bean
        QueryWrapper<Routerrule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rulename",tradeCode);
        Routerrule routerrule = routerRuleDao.selectOne(queryWrapper);
        String beanName = routerrule.getTarget();


        IRouter router = (IRouter)BeanFactoryHelper.getBean(beanName);

        return router.router(map, response);
    }

}
